package com.llc.port.config;

import java.util.Iterator;
import java.util.Set;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.ObjectName;
import javax.management.Query;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 *	 获取当前项目运行端口号---整合
 * @author linlvcao
 * @email 1013573731@qq.com
 * @time 2019年12月16日 下午4:39:51
 *
 */
@Component
public class PortConfig implements ApplicationListener<WebServerInitializedEvent> {
	
	private Integer port = 0;
	
	/**
	 * 	对外获取当前项目端口
	 * @return
	 */
	public Integer getProPort() {
		if (this.port == 0) {	//	表明当前项目运行在第三方插件(如tomcat)
			this.port = getPort();
		}
		return this.port;
	}

	@Override
	public void onApplicationEvent(WebServerInitializedEvent event) {
		this.port = event.getWebServer().getPort();
	}
	
	/**
	 * 	第三方获取项目端口
	 * @return
	 */
	private int getPort() {
    	try {
            MBeanServer server;
            if (MBeanServerFactory.findMBeanServer(null).size() > 0) {
                server = MBeanServerFactory.findMBeanServer(null).get(0);
            } else {
                return -1;
            }
     
            Set<ObjectName> names = server.queryNames(new ObjectName("Catalina:type=Connector,*"),
                    Query.match(Query.attr("protocol"), Query.value("HTTP/1.1")));
     
            Iterator<ObjectName> iterator = names.iterator();
            if (iterator.hasNext()) {
                ObjectName name = iterator.next();
                return Integer.parseInt(server.getAttribute(name, "port").toString());
            }
        } catch (Exception e) {
        	e.printStackTrace();
        }
        return -1;

    }

}
